package com.mustafaiev.tair.cts.validation;

import org.apache.log4j.Logger;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

import com.mustafaiev.tair.cts.dto.PayerDTO;
import com.mustafaiev.tair.cts.exeption.DataNotRetrievedException;
import com.mustafaiev.tair.cts.service.PayerService;

public class PayerValidator implements ICostsTrackingSystemValidator {

	private static final Logger LOGGER = Logger.getLogger(PayerValidator.class);

	private final PayerService payerService;

	public PayerValidator(final PayerService payerService) {
		this.payerService = payerService;
	}

	@Override
	public void validate(final Object obj, final Errors error) {
		final PayerDTO payer = (PayerDTO) obj;
		ValidationUtils.rejectIfEmpty(error, "email",
				"cts.validator.payer.wrong.email");
		ValidationUtils.rejectIfEmpty(error, "firstname",
				"cts.validator.payer.wrong.firstname");
		ValidationUtils.rejectIfEmpty(error, "lastname",
				"cts.validator.payer.wrong.lastname");
		ValidationUtils.rejectIfEmpty(error, "password",
				"cts.validator.payer.wrong.password");
		try {
			if (this.payerService.isPayerExists(payer.getEmail())) {
				error.reject("cts.validator.payer.exists");
			}
		} catch (final DataNotRetrievedException e) {
			LOGGER.error(e.getLocalizedMessage(), e);
		}
	}

	@Override
	public boolean supports(final Class<?> obj) {
		return obj.equals(PayerDTO.class);
	}

}
